package the.broccoli.weixin.service.support;

import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.wisteria.framework.util.MoneyUtil;
import org.wisteria.framework.web.BusinessException;
import the.broccoli.weixin.service.dto.WeiXinCreateRefundDTO;
import the.broccoli.weixin.service.dto.WeiXinCreateRefundResultDTO;

import javax.annotation.Resource;

@Slf4j
@Component
public class WeiXinRefundSupport {

    @Resource
    private WxPayService wxPayService;

    public WeiXinCreateRefundResultDTO createRefund(WeiXinCreateRefundDTO dto) throws WxPayException {
        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
//        refundRequest.setTransactionId(dto.getOutTransactionId());
        refundRequest.setOutTradeNo(dto.getOrderId() + "");
        refundRequest.setOutRefundNo(String.valueOf(dto.getRefundId()));
        refundRequest.setTotalFee(MoneyUtil.yuan2Fen(dto.getRefundFee()));
        refundRequest.setRefundFee(MoneyUtil.yuan2Fen(dto.getRefundFee()));
        refundRequest.setNotifyUrl(dto.getNotifyUrl());
        WxPayRefundResult result = null;
        try {
            result = wxPayService.refund(refundRequest);
        } catch (WxPayException we) {
            log.error("发起退款错误", we);
            throw BusinessException.withErrorCode(we.getErrCodeDes());
        } catch (Exception e) {
            log.error("发起退款异常", e);
            throw BusinessException.withErrorCode("退款异常，请稍后重试");
        }

        WeiXinCreateRefundResultDTO refundResult = new WeiXinCreateRefundResultDTO();
        refundResult.setOutRefundId(result.getRefundId());
        refundResult.setTransactionId(result.getTransactionId());
        return refundResult;
    }
}
